package chapter12;

/**
 * @author yuhui
 * descriptions:
 * @create 2024 - 12 - 19 8:17 下午
 */

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;

public class MysqlUtils {

    // JDBC URL, 用户名和密码
    private static final String JDBC_URL = "jdbc:mysql://localhost:3306/bigdata";
    private static final String JDBC_USER = "root";
    private static final String JDBC_PASSWORD = "yuhui888";
    private static final String your_table_name = "view01";

    public static void main(String[] args) {

        ArrayList<View> list = new ArrayList<View>();

        list.add(new View("11", "21"));
        list.add(new View("12", "22"));
        list.add(new View("13", "23"));
        list.add(new View("14", "24"));

        String sql = "INSERT INTO " + your_table_name + " (category , hot ) VALUES (?, ?)";

        insetData(list, sql);
    }

    public static void insetData(ArrayList<View> list, String sql) {
        Connection connection = null;
        PreparedStatement preparedStatement = null;

        try {
            // 1. 加载MySQL JDBC驱动（在 Java 6 及以上版本中通常不需要显式加载，因为 JDBC 4.0 自动加载驱动）
            // Class.forName("com.mysql.cj.jdbc.Driver");

            // 2. 建立数据库连接
            connection = DriverManager.getConnection(JDBC_URL, JDBC_USER, JDBC_PASSWORD);

            // 3. 创建SQL语句（注意：这里不要设置参数值，因为我们将在循环中设置）
            preparedStatement = connection.prepareStatement(sql);

            // 4. 遍历列表并设置参数值，添加到批处理中
            for (View view : list) {
                preparedStatement.setString(1, view.getF1());
                preparedStatement.setString(2, view.getF2());
                preparedStatement.addBatch();
            }

            // 5. 执行批处理
            int[] rowsAffected = preparedStatement.executeBatch();
            if (rowsAffected.length > 0) {
                System.out.println("数据批量插入成功！插入了 " + rowsAffected.length + " 条记录。");
            } else {
                System.out.println("数据插入失败。");
            }

        } catch (SQLException e) {
            System.out.println("数据库连接失败或SQL执行错误！");
            e.printStackTrace();
        } finally {
            // 6. 关闭资源
            try {
                if (preparedStatement != null) preparedStatement.close();
                if (connection != null) connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

}